package com.zjitc.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjitc.reggie.common.CustomException;
import com.zjitc.reggie.dto.DishDto;
import com.zjitc.reggie.entity.*;
import com.zjitc.reggie.service.CategoryService;
import com.zjitc.reggie.service.DishFlavorService;
import com.zjitc.reggie.service.DishService;
import com.zjitc.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);
        //"records" 属性通常代表当前分页查询结果的记录列表
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //把一个一个数据拷贝到dishDto
            BeanUtils.copyProperties(item, dishDto);
            //通过id查分类名
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdwithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    @GetMapping("list")
    public R<List<Dish>> list(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }

    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        // 查看有没有被套餐使用
        int count = this.getCount(ids);
        if (count > 0) {
            throw new CustomException("该菜品正在套餐中售卖 无法进行删除");
        }
        // 需要将其口味信息一并进行删除

        ids.forEach((id) -> {
            Dish dish = dishService.getById(id);
            if (dish.getStatus() == 1) {
                throw new CustomException("正在售卖中无法删除");
            }
        });

        ids.stream().forEach((item) -> {
            // 删除菜品
            dishService.removeById(item);
            // 删除菜品关联的口味信息
            QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
            wrapper.eq("dish_id", item);
            dishFlavorService.remove(wrapper);
        });

        return R.success("删除成功！！");
    }

    private int getCount(List<Long> ids) {
        // 在停售前先查看是否在其套餐中使用
        QueryWrapper<SetmealDish> wrapper = new QueryWrapper<>();
        wrapper.in("dish_id", ids);

        int count = setmealDishService.count(wrapper);
        return count;
    }

    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") int status, @RequestParam("ids") List<Long> ids) {
        int count = getCount(ids);
        if (count > 0) {
            // 表示该菜品在其套餐中不能进行删除
            throw new CustomException("菜品在其套餐中使用无法进行停售");
        }
        ids.stream().forEach((item) -> {
            Dish dish = dishService.getById(item);
            dish.setStatus(status);
            dishService.updateById(dish);
        });

        return R.success("修改成功");
    }

}
